var amapFile = require('../../utils/amap-wx.130.js');
var gaode_key = require('../../utils/config');
Page({
  data: {
    markers: [],
    latitude_e: '', // 出发地x
    longitude_e: '', // 出发地y
    latitude: '',//目的地x
    longitude: '',//目的地y
    textData: {},
    polyline: [],
    includePoints: [],
    distance: '',
    daohang: false,
    mapState: true,
    keyword:'',
    distance:'',//配送距离
    duration:'',//配送时间
    mi:''
  },
   //计算时间
   estimateTravelTime(distanceMeters) {
    // 转换为千米
    const distanceKm = distanceMeters / 1000;  
    let speed;
    speed =15;//骑行时间
    // 计算时间（小时）
    const timeHours = distanceKm / speed;  
    // 转换为分钟并添加缓冲时间
    let timeMinutes = timeHours * 60;
    return Math.round(timeMinutes);
  },
   // 输入框内容变化
   onInput(e) {
    this.setData({ keyword: e.detail.value });
  },
  calculateStraightDistance() {
    const toRadians = angle => angle * Math.PI / 180;
    
    const lat1 = toRadians(this.data.latitude_e);
    const lon1 = toRadians(this.data.longitude_e);
    const lat2 = toRadians(this.data.latitude);
    const lon2 = toRadians(this.data.longitude);
    
    // Haversine公式
    const dLat = lat2 - lat1;
    const dLon = lon2 - lon1;
    
    const a = 
      Math.sin(dLat/2) ** 2 + 
      Math.cos(lat1) * Math.cos(lat2) * 
      Math.sin(dLon/2) ** 2;
    
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    
    // 地球半径（米）
    const R = 6371000;
    return R * c;
  },
  // 搜索位置
  searchLocation() {
    const that = this;
    const myAmap = new amapFile.AMapWX({
      key:  gaode_key.Config.key// 替换为你的Key
    });
    // 关键词搜索
    myAmap.getPoiAround({
      querykeywords: that.data.keyword,
      success: (res) => {
        if (res.markers && res.markers.length > 0) {
          const firstResult = res.markers[0];
          const pois=res.poisData[0];
          console.log(pois);
          that.setData({
            textData:pois,
            longitude_e: firstResult.longitude,
            latitude_e: firstResult.latitude,
            markers: [{
              ...firstResult,
              title: firstResult.name,
              iconPath: '/images/marker.png', // 自定义标记图标
              width: 30,
              height: 30
            }]
          });
        }
        const mi= this.calculateStraightDistance();
        const time=this.estimateTravelTime(mi);
        let str=Math.round(mi)+'';
        let ifout=true;//判断是否超出范围
        if(str.length>=4&&str.length<5){
          let qian=str.charAt(0);
          if(qian>=8){
            //大于八公里超出配送范围
            ifout=false;
          }else{
            str=str.substring(1,str.length); 
          str=qian+"."+str;
          }
        }
        this.setData({
          distance:ifout?str:ifout,
          duration:time,
          mi:Math.round(mi)
        })
      },
      fail: (err) => {
        console.error('搜索失败', err);
        wx.showToast({ title: '搜索失败，请重试', icon: 'none' });
      }
    });
  },
  // 地点搜索 如果搜索目的地搜索导航
  getPoiData: function () {
    const that = this;
    var myAmap = new amapFile.AMapWX({
      key: gaode_key.Config.key
    });
    myAmap.getPoiAround({
      querykeywords:'南塘小学',
    //   querykeywords:'中信广场',
      success: (res) => {
        if (res.markers && res.markers.length > 0) {
          const firstResult = res.markers[0];
          that.setData({
            longitude: firstResult.longitude,
            latitude: firstResult.latitude,
            markers: [{
              ...firstResult,
              title: firstResult.name,
              iconPath: '/images/marker.png', // 自定义标记图标
              width: 30,
              height: 30
            }]
          });
        }
      },
      fail: (err) => {
        console.error('搜索失败', err);
        wx.showToast({ title: '搜索失败，请重试', icon: 'none' });
      }
    });
  },
  onLoad: function () {
   this.setData({
    keyword:'湖南托雅技工学校'
   })
   this.getPoiData() 
   this.searchLocation();
  },
  //返回上一个页面
  goback(){
    const eventChannel = this.getOpenerEventChannel();
    const then=this;
    eventChannel.emit('backEvent', { 
      obj: then.data.textData,
      distance:this.data.distance,
      duration:this.data.duration,
      mi:this.data.mi
    })
    wx.navigateBack();
  }

})